<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="elem">ById</div>

    <div class="classes">classes 1</div>
    <div class="classes">classes 2</div>

    <input type="text" name="text" />
    <input type="text" name="username" />

    <h1>标题</h1>

    <div class="contents">
      <ul class="book">
        <li class="chapter">Chapter 1</li>
        <li class="chapter">Chapter 2</li>
      </ul>
    </div>

    <script>
      // 通过 id 获取元素
      const elem = document.getElementById("elem");
      console.log(elem);

      // 通过类名查找
      const cls = document.getElementsByClassName("classes");
      console.log(cls);

      // 通过类型查找
      const names = document.getElementsByName("text");
      console.log(names);

      // 通过标签名查找
      const tagNames = document.getElementsByTagName("h1");
      console.log(tagNames);

      // 根据命名空间查找元素名称
      var tagNameNS = document.getElementsByTagNameNS(
        "http://www.w3.org/1999/xhtml",
        "h1"
      );
      console.log(tagNameNS);

      const _elem = document.querySelector("#elem");
      const _cls = document.querySelectorAll(".classes");
      const _names = document.querySelectorAll("[name=text]");
      const _tagNames = document.querySelectorAll("h1");
      const _tagNameNs = Array.from(document.querySelectorAll("h1")).filter(
        (el) => el.namespaceURI === "http://www.w3.org/1999/xhtml"
      );
      console.log(_elem, _cls, _names, _tagNameNs, _tagNameNs);

      // 上述方法都是搜索 DOM

      // el.mathes(css) 通过检查与给定的 CSS 选择器匹配。返回 true 或 false
      const inputs = document.getElementsByTagName("input");
      Array.from(inputs).forEach((inp) => {
        if (inp.matches("[name=text]")) {
          console.log("匹配");
        } else {
          console.log("不匹配");
        }
      });

      // closest：元素的祖先
      let chapter = document.querySelector(".chapter"); // LI

      console.log(chapter.closest(".book")); // UL
      console.log(chapter.closest(".contents")); // DIV

      console.log(chapter.closest("h1")); // null（因为 h1 不是祖先）
    </script>
  </body>
</html>
